<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>封装JSONP</title>
  </head>

  <body>
    <button id="btn1">点击发送JSONP请求</button>
    <button id="btn2">点击发送JSONP请求</button>
  </body>
  <script>
    // function fn(data) {
    //   console.log("我是全局函数fn");
    //   console.log(data);
    // }
  </script>
  <script>
    let btn1 = document.querySelector("#btn1");
    let btn2 = document.querySelector("#btn2");

    btn1.onclick = function (options) {
      JSONP({
        url: "http://localhost:3001/better",
        // 一.处理服务端返回的数据，让它和fn函数产生关联(替代fn函数)
        data: {
          name: "tom",
          age: 20
        },
        success: function (data) {
          console.log("123");
          console.log(data);
        }
      });
    }

    btn2.onclick = function (options) {
      JSONP({
        url: "http://localhost:3001/better",
        // 四.JSONP传递参数
        data: {
          name: "jason",
          age: 18
        },
        // 一.处理服务端返回的数据，让它和fn函数产生关联(替代fn函数)
        success: function (data) {
          console.log("456");
          console.log(data);
        }
      });
    }

    function JSONP(options) {
      // 1.创建script标签
      let script = document.createElement("script")
      // 2.获取body
      let body = document.body;
      // 五.处理传过来的data
      let params = "";
      for (let attr in options.data) {
        params += "&" + attr + "=" + options.data[attr];
      }
      
      // 三.获取函数名(给每一个函数一个独一无二的名字)
      let fnName = "myJSONP" + Math.random().toString().replace(".", '');
      //二.封装全局函数(解决不是全局函数不能访问的问题)
      window[fnName] = options.success;
      // 3.设置script的src的值
      script.src = options.url + "?callback=" + fnName + params;
      // 4.在body里添加script标签
      body.appendChild(script);
      // 5.优化：删除script标签
      script.onload = () => {
        body.removeChild(script);
      }
    }
  </script>

</html>